﻿using AutoMapper;
using MediatR;
using MyRabbit.Application.Command.ImgCommand;
using MyRabbit.Application.ErrorCode;
using MyRabbit.Domain;
using MyRabbit.Repositories;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Transactions;

namespace MyRabbit.Application.CommandHandler.ImgCommandHandler
{
    public class ImgDelCommandHandler : IRequestHandler<ImgDelCommand, APIResult<object>>
    {
        private readonly IRepository<ImgInfo> imginfoRep;
        private readonly IRepository<ImgInfos> imginfosRep;
        private readonly IMapper mapper;

        public ImgDelCommandHandler(IRepository<ImgInfo> imginfoRep, IMapper mapper, IRepository<ImgInfos> imginfosRep)
        {
            this.mapper = mapper;
            this.imginfoRep = imginfoRep;
            this.imginfosRep = imginfosRep;
        }

        public async Task<APIResult<object>> Handle(ImgDelCommand request, CancellationToken cancellationToken)
        {
            APIResult<object> result = new APIResult<object>();
            result.Code = Codes.删除成功;
            result.Message = Codes.删除成功.ToString();

            using (TransactionScope scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
            {
                try
                {
                    ImgInfo imgInfo = await imginfoRep.GetByIdAsync(Convert.ToInt32(request.Id));
                    if (imgInfo == null)
                    {
                        result.Code = Codes.删除失败;
                        result.Message = Codes.删除失败.ToString() + "图片不存在";
                        return await Task.FromResult(result);
                    }
                    await imginfoRep.DeleteAsync(imgInfo);

                    ImgInfos imginfos = await imginfosRep.GetByConditionAsync(x => x.ImgId == imgInfo.ImgId);

                    if (imginfos != null)
                    {
                        await imginfosRep.DeleteAsync(imginfos);
                    }
                    //提交事务
                    scope.Complete();
                    return await Task.FromResult(result);
                }
                catch (Exception ex)
                {
                    result.Code = Codes.删除失败;
                    result.Message = Codes.删除失败 + ex.Message;
                }
            }
            return await Task.FromResult(result);

        
        }
    }
}
